/*
 * Copyright 2007-2008 Brian Cavalier
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package  org.bc.iterate.io;

import org.bc.iterate.view.AbstractView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.IOException;

/**
 * A StreamView iterates over lines of text read from an {@link java.io.InputStream},
 * {@link java.io.Reader}, etc.  Internally it uses {@link java.io.BufferedReader#readLine()}  to
 * read lines of text from the associated stream.
 * 
 * @author Brian Cavalier
 */
@SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
public class StreamView extends AbstractView<String>
{
	private BufferedReader reader;
	private String line;
	private boolean close = false;
	
	public StreamView(InputStream s, boolean close) {
		this(new BufferedReader(new InputStreamReader(s)), close);
	}
	
	public StreamView(Reader r, boolean close) {
		setReader(new BufferedReader(r));
        setClose(close);
    }
		
	public boolean hasNext() {
        //noinspection UnusedCatchParameter
        try {
			setLine(getReader().readLine());
			return (getCurrentLine() != null);
		} catch(IOException e) {
			if(willClose()) {
				try {
					getReader().close();
				} catch(IOException ignored) {}
			}
			setLine(null);
			return false;
		}
	}
	
	@SuppressWarnings({"IteratorNextCanNotThrowNoSuchElementException"})
    public String next() {
		return getCurrentLine();
	}

    public BufferedReader getReader()
    {
        return reader;
    }

    private void setReader(BufferedReader reader)
    {
        this.reader = reader;
    }

    public String getCurrentLine()
    {
        return line;
    }

    private void setLine(String line)
    {
        this.line = line;
    }

    public boolean willClose()
    {
        return close;
    }

    public void setClose(boolean close)
    {
        this.close = close;
    }
}
